package com.example.controller;

import com.example.service.FileService;
import com.example.utils.AliyunOSSUtil;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by lightClouds917
 * Date 2018/2/7
 * Description:文件上传
 */
@RestController
@RequestMapping("//upload")
public class UploadController {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 文件上传
     * @param file
     */
    @Resource
    private FileService fileService;

    @RequestMapping(value = "uploadBlog",method = RequestMethod.POST)
    public String uploadBlog(MultipartFile file){

//        logger.info("============>文件上传");
        try {
            if(null != file){
                String filename = file.getOriginalFilename();
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    logger.info(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = AliyunOSSUtil.upload(newFile);
                    fileService.update1(filename,uploadUrl);
                }

            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return "上传成功";
    }

    @RequestMapping(value = "toUploadBlog",method = RequestMethod.GET)
    public String toUploadBlog(){
        return "upload";
    }

}
